import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
# 读取图片，0表示灰度图像
img = cv2.imread('hanzi1.jpg', 0)
img1=cv2.imread('hanzi1.jpg')
thresh_hold, new_img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
thresh_inv = cv2.bitwise_not(new_img)
kernel = np.ones((3, 3), np.uint8)

# 进行腐蚀操作，迭代3次增强腐蚀效果
eroded_img = cv2.erode(thresh_inv, kernel,iterations=4)
kernel1 = np.ones((15,15), np.uint8)
dilated_img = cv2.dilate(eroded_img, kernel1,iterations=3)
kernel2 = np.ones((75, 75), np.uint8)
closed_img = cv2.morphologyEx(dilated_img , cv2.MORPH_CLOSE, kernel2)
lower = 100
upper = 300
img_blur = cv2.GaussianBlur(closed_img,(5,5), 0) #高斯滤波
edges_with_blur = cv2.Canny(img_blur, lower, upper)


contours, hierarchy = cv2.findContours(edges_with_blur, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


# 遍历轮廓列表
for index, c in enumerate(contours):
    perimeter = cv2.arcLength(c, True)
    x, y, w, h = cv2.boundingRect(c)

    # 根据周长阈值筛选并绘制边界框
    if perimeter > 100:
        char_img = img[y:y + h, x:x + w]  # 提取汉字图像
        char_filename = os.path.join('chars', f'char_{index + 1}.jpg')  # 生成文件名
        cv2.imwrite(char_filename, char_img)  # 保存汉字图像
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

fg, ax = plt.subplots(1, 7, figsize=(15, 5))

ax[0].imshow(img1, cmap='gray')
ax[0].set_title("Original image")
ax[1].imshow(thresh_inv, cmap='gray')
ax[1].set_title("Binary image")
ax[2].imshow(eroded_img, cmap='gray')
ax[2].set_title("quzhao")
ax[3].imshow(dilated_img,cmap='gray')
ax[3].set_title('pengz')
ax[4].imshow(closed_img,cmap='gray')
ax[4].set_title('biyunshuan')
ax[5].imshow(edges_with_blur,cmap='gray')
ax[5].set_title('gaosi')
ax[6].imshow(img,cmap='gray')
ax[6].set_title('shibie')
# 自动调整子图参数，使子图填充整个图像区域
plt.tight_layout()
# 显示图像
plt.show()